package cn.bjxy.shishaolong.talk_room.client;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import cn.bjxy.shishaolong.talk_room.Utils;

public class ClientUI {

	private static final String SOFT_NAME = "聊天室—客户端";
	private static final String SOFT_VERTION = "V1.0.0";
	
	private JFrame frame;
	private JTextField inTalk_tField;
	private JTextField inSerIp_tField;
	private JTextField inSerPot_tField;
	private JTextField inCltPort_tField;
	private JTextField inCltIp_textField;
	
	private ClientService service; 
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ClientUI window = new ClientUI();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ClientUI() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 775, 571);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setTitle(SOFT_NAME+SOFT_VERTION+"   --By时少龙");
		frame.getContentPane().setLayout(null);
		
		final JTextArea showMsg_tArea = new JTextArea();
		
		frame.getContentPane().add(showMsg_tArea);
		showMsg_tArea.setEditable(false);
		
		//聊天文本输入框
		inTalk_tField = new JTextField();
		inTalk_tField.setBounds(25, 459, 588, 52);
		frame.getContentPane().add(inTalk_tField);
		inTalk_tField.setColumns(10);
		inTalk_tField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				//判断按键（是否按了回车键）
				if(e.getKeyCode() == KeyEvent.VK_ENTER)
					sendMessage();
			}
		});
		
		//发送按钮
		final JButton send_btn = new JButton("发送");
		send_btn.setBounds(634, 469, 96, 32);
		frame.getContentPane().add(send_btn);
		//给发送按钮添加点击事件
		send_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				sendMessage();
			}
		});

		//聊天消息框的滚动条
		JScrollPane showMsg_sPane = new JScrollPane(showMsg_tArea);
		showMsg_sPane.setBounds(25, 92, 705, 354);
		frame.getContentPane().add(showMsg_sPane);
		showMsg_sPane.setAutoscrolls(true);
		
		JLabel server_label = new JLabel("服务器");
		server_label.setBounds(25, 27, 52, 18);
		frame.getContentPane().add(server_label);
		
		JLabel serverIp_label = new JLabel("ip:");
		serverIp_label.setBounds(91, 24, 26, 18);
		frame.getContentPane().add(serverIp_label);
		
		inSerIp_tField = new JTextField();
		inSerIp_tField.setBounds(120, 21, 96, 24);
		frame.getContentPane().add(inSerIp_tField);
		inSerIp_tField.setColumns(10);
		
		inSerPot_tField = new JTextField();
		inSerPot_tField.setColumns(10);
		inSerPot_tField.setBounds(290, 21, 96, 24);
		frame.getContentPane().add(inSerPot_tField);
		
		JLabel serverPot_label = new JLabel("端口:");
		serverPot_label.setBounds(248, 24, 38, 18);
		frame.getContentPane().add(serverPot_label);
		
		inCltPort_tField = new JTextField();
		inCltPort_tField.setColumns(10);
		inCltPort_tField.setBounds(290, 55, 96, 24);
		frame.getContentPane().add(inCltPort_tField);
		
		JLabel clent_label = new JLabel("端口:");
		clent_label.setBounds(248, 58, 38, 18);
		frame.getContentPane().add(clent_label);
		
		inCltIp_textField = new JTextField();
		inCltIp_textField.setColumns(10);
		inCltIp_textField.setBounds(120, 55, 96, 24);
		frame.getContentPane().add(inCltIp_textField);
		inCltIp_textField.setText(getLocalIpAddress());
		
		JLabel cltIp_label = new JLabel("ip:");
		cltIp_label.setBounds(91, 58, 26, 18);
		frame.getContentPane().add(cltIp_label);
		
		JLabel client_label = new JLabel("客户端");
		client_label.setBounds(25, 61, 52, 18);
		frame.getContentPane().add(client_label);
		
		final JButton joinTalk_btn = new JButton("加入聊天");
		joinTalk_btn.setBounds(517, 37, 96, 27);
		frame.getContentPane().add(joinTalk_btn);
		
		//退出按钮
		final JButton quit_btn = new JButton("退出聊天");
		quit_btn.setBounds(634, 35, 96, 27);
		frame.getContentPane().add(quit_btn);

		//启动时 初始化界面组件状态
		initLockUI(send_btn, quit_btn);
		
	//==============================添加监听部分开始=================================	
		//加入聊天按钮监听
		joinTalk_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//初始化服务类中的参数
				service = new ClientService(
						Integer.parseInt(inCltPort_tField.getText()),
						inSerIp_tField.getText(),
						Integer.parseInt(inSerPot_tField.getText()),
						frame);
				//启动接受消息服务
				new Thread(service.new receiveTalk(showMsg_tArea)).start();
				//界面显示开启服务
				showMsg_tArea.append(
						new StringBuilder()
						.append(Utils.dateFormat()).append(":\n")
						.append("本机(")
						.append(inCltIp_textField.getText())
						.append(":").append(inCltPort_tField.getText()).append(")已连接到服务端(")
						.append(inSerIp_tField.getText()).append(":")
						.append(inSerPot_tField.getText()).append("),可以开始聊天了！\n")
						.toString());
				//界面组件上锁
				joinTalkLockUI(send_btn, quit_btn,joinTalk_btn);
			}
		});
		//退出聊按钮监听
		quit_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
//				new Thread(service.new CloseTalk()).start();
				service.closeTalk();
				//关闭服务后改变界面组件的状态
				quitTalkLockUI(send_btn, quit_btn, joinTalk_btn);
				//关闭服务后界面的提示信息
				showMsg_tArea.append(
						new StringBuilder("\n")
						.append(Utils.dateFormat()).append(":\n")
						.append("已退出聊天").toString());
			}
		});
	//==============================添加监听部分结束=================================	
	}


	//==============================界面组件加锁部分开始==================================
	//启动时需要改变的界面状态
	private void initLockUI(JButton send_btn, JButton quit_btn) {
		quit_btn.setEnabled(false);
		send_btn.setEnabled(false);
		inTalk_tField.setEditable(false);
	}
	//点击开始聊天时，改变界面状态
	private void joinTalkLockUI(final JButton send_btn, final JButton quit_btn, final JButton joinTalk_btn) {
		inCltIp_textField.setEditable(false);
		inCltPort_tField.setEditable(false);
		inSerIp_tField.setEditable(false);
		inSerPot_tField.setEditable(false);
		inTalk_tField.setEditable(true);
		quit_btn.setEnabled(true);
		joinTalk_btn.setEnabled(false);
		send_btn.setEnabled(true);
	}
	//点击退出聊天时，改变界面状态
	private void quitTalkLockUI(final JButton send_btn, final JButton quit_btn, final JButton joinTalk_btn) {
		inCltIp_textField.setEditable(true);
		inCltPort_tField.setEditable(true);
		inSerIp_tField.setEditable(true);
		inSerPot_tField.setEditable(true);
		inTalk_tField.setEditable(false);
		quit_btn.setEnabled(false);
		joinTalk_btn.setEnabled(true);
		send_btn.setEnabled(false);
	}
	
	//==============================界面组件加锁部分结束==================================

	
	//获取到本机ip地址
	private String getLocalIpAddress() {
		String loopIp = "172.0.0.1";
		String ip = loopIp;
		try {
			InetAddress localHost = InetAddress.getLocalHost();
			ip = localHost.getHostAddress();
		} catch (UnknownHostException e) {
			ip = loopIp;
			e.printStackTrace();
		}
		return ip;
	}

	//发送消息方法
	private void sendMessage() {
		service.sendMessage(inTalk_tField.getText());
		inTalk_tField.setText("");
	}
}
